using Microsoft.AspNetCore.Mvc;
using MvcSoft2Demo.Repository;
using MvcSoft2Demo.Models;
using System.Linq;
using MvcSoft2Demo.RequestParams;
using System.Collections.Generic;

namespace MvcSoft2Demo.Controllers
{
    public class TestController : Controller
    {
        public IActionResult Index()
        {
            // 判断学校有没有记录，如果没有，则插入一条记录
            var schoolRep = new EfRepository<School>();
            var school = schoolRep.Table.FirstOrDefault();
            if (school == null)
            {
                schoolRep.Insert(new School
                {
                    SchoolName = "闽大"
                });
            }
            var studentRep = new EfRepository<Student>();
            var students = studentRep.Table.Where(x => x.IsDeleted == false).ToList();
            return View(students);
        }

        public IActionResult CreateOrEdit()
        {
            return View();
        }
        public IActionResult Save(StudentParam request)
        {
            var studentRep = new EfRepository<Student>();
            // id大于0，说明是编辑；否则为新增
            if (request.Id > 0)
            {

            }
            else
            {
                studentRep.Insert(new Student
                {
                    StudentName = request.Name,
                    SchoolId = 1
                });
            }
            return Ok();
        }

        public IActionResult Query(QueryParam request)
        {
            var studentRep = new EfRepository<Student>();
            var keyword = request.Keyword!=null? request.Keyword.Trim():"";
            var students=studentRep.Table.Where(x=>x.IsDeleted==false);

            if(keyword.Length>0){
                students=students.Where(x=>x.StudentName.Contains(keyword));
            }
            
            return Json(students.ToList());
        }
    }
}